import { Router } from "express";
import * as Controller from "../api/controllers/user.controller";
import * as UserService from "../api/services/user.service";
import jwt from "jsonwebtoken";
import passport from "passport";
import { SECRET_KEY } from "../config/constants";

const router = Router();

router.route("/").get(Controller.getUsers);

router.route("/:id").get(Controller.getUserById);

router.route("/").post(Controller.addUser);

router.route("/:id").put(Controller.updateUserById);

router.route("/:id").delete(Controller.deleteUserById);

router.route("/upload").post(Controller.upload);

router.route("/info/:userToken").get(Controller.getUserByToken);

router.post("/login", async (req, res) => {
  const employeeId: string = req.body.employeeId;
  const password: string = req.body.password;

  try {
    await UserService.getUserByEmployeeId(employeeId).then(async (user: any) => {
      if (!user || user.length === 0) {
        return res.status(404).json("用户不存在!");
      }

      if (password === user[0].userPassword) {
        const rule = {
          id: user[0].id,
          userName: user[0].userName,
        };
        jwt.sign(
          rule,
          SECRET_KEY,
          { expiresIn: 3600 },
          async (err: any, token: string) => {
            if (err) throw err;

            user[0].userToken = "Bearer " + token;
            await UserService.updateUser({
              ...user[0],
              id: user[0].id,
            });

            res.status(200).json({
              data: {
                token: "Bearer " + token,
              },
              code: 2000,
            });
          }
        );
      } else {
        return res.status(400).json("密码错误!");
      }
      // });
    });
  } catch (err) {
    console.error(
      "[login][Error] ",
      typeof err === "object" ? JSON.stringify(err) : err
    );
    res.status(500).json({
      message: "登录失败！",
    });
  }
});

router.post("/logout", async (req, res) => {
  res.status(200).json({
    data: "success",
    code: 2000,
  });
});

// @route  GET api/users/current
// @desc   return current user
// @access Private
router.get(
  "/current",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    res.json({
      id: JSON.stringify(req.user),
    });
  }
);

export default router;
